<!--
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-08-03 17:02:33
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-21 14:59:02
 * @Description:
 *
-->
<template>
  <el-dialog
    class="upload-app-dialog"
    :title="title"
    :visible="show"
    width="50%"
    top="15vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeClick"
  >
    <el-form
      ref="uploadForm"
      style="margin-right: 50px; margin-left: 50px"
      :rules="rules"
      :model="form"
      label-width="auto"
    >
      <el-form-item label="集群服务商" prop="cloudVendor">
        <el-select
          v-model="form.cloudVendor"
          size="small"
          :disabled="isEdit"
          placeholder="请选择集群服务商"
          style="width: 100%"
        >
          <el-option
            v-for="item in cloudVendors"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="!isEdit"
        style="width: 150px; float: left"
        class="upload-file"
        prop="clusterConfigure"
        label="添加集群配置文件"
      />
      <el-steps v-if="!isEdit" direction="vertical" :active="0">
        <el-step title="下载配置文件">
          <template slot="description">
            <span style="font-size: 14px">cnap-admin.yaml</span>
            <el-button
              class="updataButton"
              size="mini"
              type="primary"
              icon="el-icon-download"
              @click="downloadDoc"
            >下载</el-button>
          </template>
        </el-step>
        <el-step
          title="上传配置文件到待注册的服务器，并在文件目录下执行如下脚本"
        >
          <template slot="description">
            <el-input
              id="demoInput"
              v-model="configure"
              style="width: 625px"
              disabled
            >
              <el-button
                slot="append"
                style=""
                size="mini"
                @click="handleCopyText()"
              >复制</el-button>
            </el-input>
          </template>
        </el-step>
        <el-step title="将脚本运行结果上传至平台，进行集群配置">
          <template slot="description">
            <el-form-item
              prop="configureInfo"
              style="position: relative; right: 17.6%"
            >
              <el-input
                id="demoInput"
                v-model="form.configureInfo"
                style="width: 625px"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
              />
            </el-form-item>
          </template>
        </el-step>
      </el-steps>
      <el-form-item
        style="margin-top: 20px"
        label="集群名称"
        prop="cloudVendorName"
      >
        <el-input
          v-model="form.cloudVendorName"
          :disabled="isEdit"
          size="small"
          placeholder="请输入集群名称"
        />
      </el-form-item>
      <el-form-item label="集群ip" prop="k8sClusterIp">
        <el-input
          v-model="form.k8sClusterIp"
          size="small"
          :disabled="isEdit"
          placeholder="请输入集群ip"
        />
      </el-form-item>
      <el-form-item label="集群描述" prop="description">
        <el-input
          v-model="form.description"
          maxlength="100"
          rows="4"
          type="textarea"
          show-word-limit
          placeholder="请输入集群描述"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelClick">取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :loading="confirmLoading"
        @click="confirmClick"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { CLUSTER_AREA } from '@/utils/cnap/constant'
import { parseIpToBinary } from '@/utils/utils'
import { addK8sCluster, editK8sClusterInfo } from '@/api/cnap/hybrid-cloud'
import { mapGetters } from 'vuex'
import cloudVendorHandle from '@/views/mixin/cloudVendorHandle.js'

export default {
  name: 'UploadAppDialog',
  components: {},
  mixins: [cloudVendorHandle],
  props: {
    show: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    appInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    /**
     * @description: 参数校验
     * @description: 集群ip
     * @return {*}
     */
    var checkIP = (rule, value, callback) => {
      if (value !== '' && value !== undefined && value !== null) {
        if (value === '0.0.0.0') {
          callback(new Error('IP不能为0.0.0.0'))
        } else {
          const reg =
            /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/
          if (!reg.test(value)) {
            callback(new Error('请输入正确的源IP地址'))
          } else {
            if (value.indexOf('/') > -1) {
              const ipArray = value.split('/')
              const ipAddr = ipArray[0]
              const netMask = ipArray[1]
              if (
                parseIpToBinary(ipAddr).lastIndexOf('1') + 1 <=
                parseInt(netMask)
              ) {
                callback()
                return true
              } else {
                callback(new Error('请输入正确的源IP地址'))
              }
            } else {
              callback()
              return true
            }
          }
        }
      } else {
        callback(new Error('IP地址不能为空'))
      }
    }
    return {
      // 配置文件复制信息
      configure:
        "kubectl apply -f cnap-admin.yaml 1>/dev/null;echo $(kubectl get secrets $(kubectl get secret -n kube-system|grep cnap-admin-token | awk '{print $1}') -n kube-system -o jsonpath={'.data.token'}|base64 -d)",
      location: [], // 区域
      areaOptions: CLUSTER_AREA, // 区域列表
      title: '注册集群', // 标题
      rules: {
        // 校验
        cloudVendorName: [
          // 集群名称
          { required: true, message: '请输入集群名称', trigger: 'blur' },
          {
            type: 'string',
            max: 20,
            message: '用户名最多20个字符！',
            trigger: 'blur'
          }
        ],
        configureInfo: [
          // 配置参数
          { required: true, message: '请配置集群参数', trigger: 'blur' }
        ],
        k8sClusterIp: [
          // K8sIP
          { required: true, validator: checkIP, trigger: 'blur' }
        ],
        cloudVendor: [
          // 集群供应商
          { required: true, message: '请选择服务商分类', trigger: 'blur' }
        ],
        area: [
          // 区域
          { required: true, message: '请选择区域版本', trigger: 'blur' }
        ],
        description: [
          // 描述
          { required: true, message: '请输入集群描述', trigger: 'blur' }
        ],
        pmax: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        pidle: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        cpuCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        diskCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        gpuCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        fileCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        fpgaCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        netCost: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        clusterConfigure: [
          // 收费标准
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      form: {
        clusterConfigure: '0', // 自动填充
        cloudVendor: '', // 集群供应商
        cloudVendorName: '', // 集群名称
        area: '', // 区域
        description: '', // 描述
        k8sClusterIp: '', // ip
        configureInfo: '', // 配置
        pmax: '0', // 收费
        pidle: '0', // 收费
        cpuCost: '0', // 收费
        cpuCostUnit: '元/月', // 收费列表单位
        diskCost: '0', // 收费
        diskCostUnit: '元/GB/月', // 收费列表单位
        gpuCost: '0', // 收费
        gpuCostUnit: '元/月', // 收费列表单位
        fileCost: '0', // 收费
        fileCostUnit: '元/GB/月', // 收费列表单位
        fpgaCost: '0', // 收费
        fpgaCostUnit: '元/月', // 收费列表单位
        netCost: '0', // 收费
        netCostType: '固定带宽', // 收费列表单位
        netCostUnit: '元/Mbps/小时' // 收费列表单位
      },
      confirmLoading: false
    }
  },
  computed: {
    ...mapGetters(['userName']),
    /**
     * @description: 云商参数
     * @return {*}
     */
    cloudVendorValue() {
      return this.form.cloudVendor
    }
  },
  watch: {
    isEdit: {
      // 编辑模式
      handler(newVal) {
        if (newVal) {
          // 赋值
          this.title = '编辑集群'
          this.form.cloudVendorName = this.appInfo.k8sClusterName // 集群名称
          this.form.cloudVendor = this.formatVendorAccount(
            this.appInfo.cloudVendor,
            this.appInfo.accountName
          ) // 集群供应商
          this.form.area = this.appInfo.k8sClusterLocation // 区域
          this.form.description = this.appInfo.k8sClusterDescribe // 描述
          this.form.k8sClusterIp = this.appInfo.k8sClusterIp // ip
          this.location = this.form.area ? this.form.area.split('/') : [] // 区域加载
          this.form.pmax = this.appInfo.pmax // 收费
          this.form.pidle = this.appInfo.pidle // 收费
          this.form.cpuCost = this.appInfo.cpuCost // 收费
          this.form.cpuCostUnit = this.appInfo.cpuCostUnit // 收费
          this.form.diskCost = this.appInfo.diskCost // 收费
          this.form.diskCostUnit = this.appInfo.diskCostUnit // 收费
          this.form.gpuCost = this.appInfo.gpuCost // 收费
          this.form.gpuCostUnit = this.appInfo.gpuCostUnit // 收费
          this.form.fileCost = this.appInfo.fileCost // 收费
          this.form.fileCostUnit = this.appInfo.fileCostUnit // 收费
          this.form.fpgaCost = this.appInfo.fpgaCost // 收费
          this.form.netCost = this.appInfo.netCost // 收费
          this.form.netCostType = this.appInfo.netCostType // 收费
          this.form.netCostUnit =
            this.appInfo.netCostType === '固定带宽'
              ? this.appInfo.netCostUnit
              : '元/GB' // 收费
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 下载文件
     * @description: 下载配置文件
     * @return {*}
     */
    downloadDoc() {
      var link = document.createElement('a')
      link.href = '/static/cnap-admin.yaml'
      link.download = 'cnap-admin.yaml'
      link.click()
      window.URL.revokeObjectURL(link.href)
    },
    /**
     * @description: 区域转化
     * @description: 转化成区域文件中的格式
     * @return {*}
     */
    cityChanged(val) {
      if (val) {
        this.form.area = val.join('/')
      } else {
        this.location = []
      }
    },
    /**
     * @description: 赋值配置
     * @description: 点击赋值
     * @return {*}
     */
    handleCopyText() {
      // 创建一个 Input标签
      const cInput = document.createElement('input')
      cInput.value = this.configure
      document.body.appendChild(cInput)
      cInput.select() // 选取文本域内容;
      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
      // Input要在正常的编辑状态下原生复制方法才会生效
      document.execCommand('Copy')
      this.$message.success('复制成功')
      // / 复制成功后再将构造的标签 移除
      cInput.remove()
    },
    /**
     * @description: 关闭页面
     * @description: X按钮关闭
     * @return {*}
     */
    closeClick() {
      this.$emit('update:show', false)
      this.fileList = null
    },
    /**
     * @description: 取消页面
     * @description: 点击取消
     * @return {*}
     */
    cancelClick() {
      this.$emit('update:show', false)
      this.$emit('cancel')
      this.fileList = null
    },
    /**
     * @description: 确定按钮
     * @description: 上传数据
     * @return {*}
     */
    confirmClick() {
      // 首先参数校验
      this.$refs.uploadForm.validate((valid, obj) => {
        if (valid) {
          this.confirmLoading = true
          if (this.isEdit) {
            // 编辑模式
            editK8sClusterInfo({
              ...this.cloudVendorParams,
              // cloudVendor: this.form.cloudVendor, // 集群供应商
              k8sClusterDescribe: this.form.description, // 描述
              k8sClusterIp: this.appInfo.k8sClusterIp, // ip
              k8sClusterName: this.form.cloudVendorName, // 集群名称
              k8sClusterLocation: this.form.area, // 区域
              pmax: this.form.pmax, // 收费标准
              pidle: this.form.pidle, // 收费标准
              cpuCost: this.form.cpuCost, // 收费标准
              cpuCostUnit: this.form.cpuCostUnit, // 收费单位
              diskCost: this.form.diskCost, // 收费标准
              diskCostUnit: this.form.diskCostUnit, // 收费单位
              gpuCost: this.form.gpuCost, // 收费标准
              gpuCostUnit: this.form.gpuCostUnit, // 收费单位
              fileCost: this.form.fileCost, // 收费标准
              fileCostUnit: this.form.fileCostUnit, // 收费单位
              fpgaCost: this.form.fpgaCost, // 收费标准
              netCost: this.form.netCost, // 收费标准
              netCostType: this.form.netCostType, // 收费单位
              netCostUnit:
                this.form.netCostType === '固定带宽'
                  ? this.form.netCostUnit
                  : '元/GB' // 收费单位
            })
              .then((res) => {
                this.$emit('update:show', false)
                this.$emit('edit-success')
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            const params = {
              // 注册模式
              k8sClusterConfig: this.form.configureInfo, // 配置文件
              ...this.cloudVendorParams,
              // cloudVendor: this.form.cloudVendor, // 集群供应商
              k8sClusterLocation: this.form.area, // 区域
              k8sClusterDescribe: this.form.description, // 描述
              k8sClusterName: this.form.cloudVendorName, // 集群名称
              k8sClusterIp: this.form.k8sClusterIp, // ip
              pmax: this.form.pmax, // 收费
              pidle: this.form.pidle, // 收费
              cpuCost: this.form.cpuCost, // 收费
              cpuCostUnit: this.form.cpuCostUnit, // 收费单位
              diskCost: this.form.diskCost, // 收费
              diskCostUnit: this.form.diskCostUnit, // 收费单位
              gpuCost: this.form.gpuCost, // 收费
              gpuCostUnit: this.form.gpuCostUnit, // 收费单位
              fileCost: this.form.fileCost, // 收费
              fileCostUnit: this.form.fileCostUnit, // 收费单位
              fpgaCost: this.form.fpgaCost, // 收费
              netCost: this.form.netCost, // 收费
              netCostType: this.form.netCostType, // 收费单位
              netCostUnit:
                this.form.netCostType === '固定带宽'
                  ? this.form.netCostUnit
                  : '元/GB' // 收费单位
            }
            addK8sCluster(params)
              .then((res) => {
                // res.code === 200正常
                if (res.code === 200) {
                  this.$Message.success('上传成功')
                  this.$emit('edit-success')
                  this.cancelClick()
                } else {
                  // 数据查询失败
                  // 输出报错信息
                  this.$Message.error(res.msg)
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.upload-app-dialog {
  .updataButton {
    margin-left: 10px;
    color: rgba(0, 145, 255, 1) !important ;
    background: rgba(217, 235, 255, 1) !important ;
    border: 1px solid rgba(0, 145, 255, 0.8);
    padding: 5px 8px !important ;
  }
  .upload-file {
    /deep/ .el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .upload-hint {
    margin-top: 10px;
    .top {
      display: flex;
      align-items: center;
      .icon {
        color: #b9b9b9;
        font-size: 17px;
        margin-right: 6px;
      }
    }
    .text {
      .textStyle(14px , 400, #C3C3C3);
      line-height: 21px;

      &.r2 {
        margin-left: 23px;
      }
    }
  }
  .selected-info {
    display: flex;
    align-items: center;
    position: relative;
    left: 10px;

    .name {
      .textStyle(14px , 500, #4a4a4a);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .icon {
      font-size: 20px;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .item {
    display: inline-block;
    width: calc(50% - 12.5px);
    &.category {
      margin-right: 25px;
    }
  }
}
</style>
<style lang="less">
.upload-app-dialog {
  .area-select.large {
    width: 100% !important;
  }
}
</style>
